package com.shaodongbo.demo_4;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView nameListView;
    private  ArrayList<Student> studentArrayList = new ArrayList<>();
    private StuAdapter adapter;
    private Button btnAddStu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initStuList();

        nameListView = findViewById(R.id.name_listView);
        adapter = new StuAdapter(MainActivity.this, studentArrayList);
        nameListView.setAdapter(adapter);

        btnAddStu = findViewById(R.id.btn_addStu);
        btnAddStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddActivity.class);
                startActivityForResult(intent, 1001);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1001 && resultCode == 2001) {
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);
            int imgID = data.getIntExtra("IMG", R.drawable.dog1);

            Student s = new Student(imgID, name, age);
            studentArrayList.add(s);
            adapter.notifyDataSetChanged();
        }
    }

    private void initStuList() {
        Student s1 = new Student(R.drawable.dog1, "张三", 18);
        Student s2 = new Student(R.drawable.dog2, "赵四", 19);
        Student s3 = new Student(R.drawable.dog3, "王五", 20);
        Student s4 = new Student(R.drawable.dog4, "赵柳", 21);
        Student s5 = new Student(R.drawable.dog5, "董卓", 22);
        studentArrayList.add(s1);
        studentArrayList.add(s2);
        studentArrayList.add(s3);
        studentArrayList.add(s4);
        studentArrayList.add(s5);
    }
}
